package zhenwoproto

import (
	"github.com/golang/glog"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"log"
	"time"
)

type Client struct {
	conn    *grpc.ClientConn
	bc      DataServiceClient
	ctx     context.Context
	timeout time.Duration
	url     string
}

func NewClient(url string, timeout string) (*Client, error) {
	// Set up a connection to the server.
	var c Client
	var err error
	c.url = url
	var to time.Duration
	if to, err = time.ParseDuration(timeout); err == nil {
		c.timeout = to
		err = c.Reset()
		return &c, err
	}
	return nil, err
}

//Reset 重置链接等
func (c *Client) Reset() (err error) {
	if c.bc != nil {
		c.conn.Close()
	}
	glog.Infoln("reconnect dataservice server")
	c.conn, err = grpc.Dial(c.url, grpc.WithInsecure())
	if err == nil {
		// Contact the server and print out its response.
		c.bc = NewDataServiceClient(c.conn)
		c.ctx = context.Background()
	}
	return
}

func (c *Client) handleErr(err error) error {
	code := grpc.Code(err)
	if code == codes.FailedPrecondition {
		glog.Errorln("reset by err", err)
		c.Reset()
	} else if code == codes.OK {
		// glog.Errorln("ok error?", err.Error())
		return nil
	} else if code != codes.Unknown {
		glog.Errorf("grpc error code %s UNHANDLED", code)
	}
	return err
}

func (c *Client) Send(in *DatacheckRequest) (*DatacheckReply, error) {
	ctx, _ := context.WithTimeout(c.ctx, c.timeout)
	r, err := c.bc.Transmission(ctx, in)
	if err != nil {
		log.Println("send_error", err)
		return nil, err
	}
	return r, nil
}
